﻿// DigitalDesign
// Project: InformationBoard
// Developer: Shirepin Andrey
// Created: 17.11.2011
// Last change: 17.11.2011
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Browser;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using Client1.PingService;
using Client1.Videoservice;
using Client1.CallBack;

/////??????using System.ComponentModel.Design;
namespace Client1
{
    public partial class MainPage : UserControl
    {
        Stack<int> freq = new Stack<int>();
        public List<Playlist> Items;
        WebClient webClient = new WebClient();
        int Current_Version = -1;
        int j = 0;
        public static DateTime CurrentTime = new DateTime();
        VideoServiceClient My_Playlist = new VideoServiceClient();
        CallbackServiceClient Send = new CallbackServiceClient();
       
        int i = 0;
        int frequency=10;//частота снятия скриншота
        public DateTime Begin_Play = new DateTime(2011,11,29,20,17,00);//время начала проигрывания видео
        public DateTime Stop_Play = new DateTime(2011, 11, 29, 20, 18, 00);//время конца проигрывания видео
        public String Videoname=@"C:\Users\Public\Videos\Sample Videos\Wildlife";
       
       
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(StartTimer);         
        }

        public void StartTimer(object o, RoutedEventArgs sender)
        {
            freq.Push(frequency);  
            System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0,1000); 
            myDispatcherTimer.Tick += new EventHandler(GO);
            myDispatcherTimer.Start();
           

        }

   // действие по таймеру
    
        
     

      

        private void GO(object sender, EventArgs e)
        {
          
            My_Disp.Play();
            CurrentTime = DateTime.Now;
            if (Videoname == null)
            {

                MessageBox.Show("No Video");
            }
            myTextBlock.Text = CurrentTime.ToString("HH:mm:ss");
           
            My_Playlist.SendPlaylistCompleted += new EventHandler<SendPlaylistCompletedEventArgs>(UpdateVideoPlaylist);
            My_Playlist.SendPlaylistAsync(1, "monday");

      
          
            
            if (CurrentTime.Hour == Items[j].Begin_play.Hour && CurrentTime.Minute == Items[j].Begin_play.Minute && CurrentTime.Second == Items[j].Begin_play.Second)
            {
                My_Disp.Play();
                MessageBox.Show("Play");
            }
            if (frequency == 0)
            {
                frequency = freq.Pop();
                frequency = 10;
                WriteableBitmap scr = new WriteableBitmap(LayoutRoot, null);
                Image screen = new Image();
                screen.Height = 50;
                screen.Margin = new Thickness(20);
                screen.Source = scr;
                thumbs.Children.Add(screen);
                i++;
                //Сохранение файла в изолированном хранилище. Проблема в том, что хранилище вмещает макс 1 мб, сответсвенно можно сохранить
                //8 изображений, после чего буфер переполняется и запись невозможна.


                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {



                    if (!store.DirectoryExists("Screen"))
                    {
                        store.CreateDirectory("Screen");
                    }
                    else
                    {

                    }


                    using (var isoStream = store.OpenFile(@"Screen\" + i, FileMode.Create))
                    {



                        byte[] buffer = MakeImage(scr);
                        //  Send.GetScreenShotAsync(1, buffer);


                        //// в данном случае предусмотрена также сохранение изображений на сервере, но из-за 
                        //// особенностей силверлайта пока закоменчено
                        /*    if (i < 7)
                            {
                               // isoStream.Write(buffer, 0, buffer.Length);
                            }
                            else
                            {
                                store.DeleteFile(@"Screen\"+(i-1));
                                isoStream.Write(buffer, 0, buffer.Length);

                            }*/
                    }
                }
            }
            if (CurrentTime.Hour == Stop_Play.Hour && CurrentTime.Minute == Stop_Play.Minute && CurrentTime.Second == Stop_Play.Second)
            { 
                My_Disp.Visibility = Visibility.Collapsed;
                My_Disp.Stop();
                MessageBox.Show("Stop");
                j++;
                if (j == Items.Count)
                {
                
                }
            }
            frequency--;
        }
        

        private static byte[] MakeImage(WriteableBitmap bitmap)
        {
            int width = bitmap.PixelWidth;
            int height = bitmap.PixelHeight;

            MemoryStream ms = new MemoryStream();

            #region BMP File Header(14 bytes)
            //(2 bytes):BM
            ms.WriteByte(0x42);
            ms.WriteByte(0x4D);

            //the size of the BMP file in bytes(4 bytes)
            long len = bitmap.Pixels.Length * 4 + 0x36;

            ms.WriteByte((byte)len);
            ms.WriteByte((byte)(len >> 8));
            ms.WriteByte((byte)(len >> 16));
            ms.WriteByte((byte)(len >> 24));


            //reserved(2 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //reserved(2 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the offset(4 bytes)
            ms.WriteByte(0x36);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            #endregion

            #region Bitmap Information(40 bytes:Windows V3)
            //the size of this header(4 bytes)
            ms.WriteByte(0x28);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the bitmap width in pixels(4 bytes)
            ms.WriteByte((byte)width);
            ms.WriteByte((byte)(width >> 8));
            ms.WriteByte((byte)(width >> 16));
            ms.WriteByte((byte)(width >> 24));

            //the bitmap height in pixels(4 bytes)
            ms.WriteByte((byte)height);
            ms.WriteByte((byte)(height >> 8));
            ms.WriteByte((byte)(height >> 16));
            ms.WriteByte((byte)(height >> 24));

            //the number of color planes(2 bytes)
            ms.WriteByte(0x01);
            ms.WriteByte(0x00);

            //the number of bits per pixel(2 bytes)
            ms.WriteByte(0x20);
            ms.WriteByte(0x00);


            //the compression method(4 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);




            #endregion

            #region Bitmap data
            for (int y = height - 1; y >= 0; y--)
            {
                for (int x = 0; x < width; x++)
                {
                    int pixel = bitmap.Pixels[width * y + x];

                    ms.WriteByte((byte)(pixel & 0xff)); 
                    ms.WriteByte((byte)((pixel >> 8) & 0xff)); 
                    ms.WriteByte((byte)((pixel >> 0x10) & 0xff)); 
                    ms.WriteByte(0x00); //reserved
                }
            }
            #endregion


            return ms.GetBuffer();
        }
        public void Get_Playlist()
        
        


             

          //  List<PlaylistWarp> begin = My_Playlist.SendPlaylistAsync(1,null);
        }
        private void UpdateVideoPlaylist(object sender, Videoservice.SendPlaylistCompletedEventArgs e)
        {
            if (e.Result != null)
            {
            


                Items = new List<Playlist>();
                for (int i = 0; i < e.Result[0].Collection.Count; i++)
                {
                    Items.Add(new Playlist(e.Result[0].Collection[i].TimeOfBegin, e.Result[0].Collection[i].TimeOfEnd, e.Result[0].Collection[i].VideoFileName));
                    Items[i].Begin_play = e.Result[0].Collection[i].TimeOfBegin;
                    Items[i].Begin_play = new DateTime(2011, 12, 4, 11, 30, 0);//это проверочные
                    Items[i].Stop_play = e.Result[0].Collection[i].TimeOfEnd;//пров
                    Items[i].Stop_play = new DateTime(2011, 12, 17, 14, 55, 0);
                    Items[i].Videoname = e.Result[0].Collection[i].VideoFileName;//пров
                    Items[i].Videoname = "loh";
                }
            }
        }
       
    }
}

